import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
	static ArrayList<Socket> clients=new ArrayList<Socket>();
	public static void main(String[] args) {
		try{
			ServerSocket server=new ServerSocket(8889);
			System.out.println("服务器已经启动......");
			while(true){
				Socket socket=server.accept();
				clients.add(socket);
				transmitMessage(socket);
			}
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	private static void transmitMessage(final Socket socket) {
		new Thread(){
			private Scanner scan;
			public void run(){
				try{
					InputStream is=socket.getInputStream();
					scan=new Scanner(is);
					socket.getOutputStream().write("连接成功...\n".getBytes());
				}catch(IOException e1){
					e1.printStackTrace();
				}
			
			while(true){
				String text=scan.nextLine()+"\n";
				for(Socket client:clients){
					try{
						OutputStream out=client.getOutputStream();
						out.write(text.getBytes());
						out.flush();
					}catch(IOException e){
						e.printStackTrace();
					}
				}
			}
		}
	}.start();
}
}